package com.xzxy.xmlg_backend.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xzxy.xmlg_backend.entity.Course;
import com.xzxy.xmlg_backend.entity.Result;
import com.xzxy.xmlg_backend.service.ICourseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/course")
public class CourseController {

    @Autowired
    private ICourseService courseService;

    @GetMapping("/page")
    public Result page(@RequestParam(defaultValue = "1") Integer page,
                       @RequestParam(defaultValue = "10") Integer size,
                       @RequestParam(required = false) String name) {
        Page<Course> pageInfo = new Page<>(page, size);
        QueryWrapper<Course> queryWrapper = new QueryWrapper<>();
        if (name != null && !name.isEmpty()) {
            queryWrapper.like("name", name);
        }
        IPage<Course> coursePage = courseService.page(pageInfo, queryWrapper);
        return Result.success(coursePage);
    }

    @PostMapping
    public Result save(@RequestBody Course course) {
        courseService.save(course);
        return Result.success();
    }

    @PutMapping
    public Result update(@RequestBody Course course) {
        courseService.updateById(course);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Long id) {
        courseService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        Course course = courseService.getById(id);
        return Result.success(course);
    }
}